<template>
  <div class="profile-page">
    <!-- 页头 -->
    <div class="page-header">
      <div class="page-title">
        <el-icon class="title-icon"><User /></el-icon>
        <span>个人信息</span>
      </div>
      <div class="page-description">查看并编辑当前登录用户的基本信息</div>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：资料卡片 -->
      <el-col :span="8">
        <el-card class="profile-card" shadow="never">
          <div class="avatar-section">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :http-request="handleAvatarUpload"
              accept="image/png,image/jpeg"
            >
              <el-avatar :size="96" :src="avatarUrl" class="avatar-large">
                {{ form.realName?.charAt(0) || form.username?.charAt(0) }}
              </el-avatar>
              <div class="avatar-tip">点击头像上传（JPG/PNG，≤2MB）</div>
            </el-upload>
          </div>

          <el-descriptions :column="1" border class="profile-desc">
            <el-descriptions-item label="用户ID">{{ form.id ?? '-' }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{ form.username || '-' }}</el-descriptions-item>
            <el-descriptions-item label="真实姓名">{{ form.realName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ form.email || '-' }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ form.phone || '-' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="form.status === 1 ? 'success' : 'danger'">{{ form.status === 1 ? '启用' : '禁用' }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="角色">
              <el-space wrap>
                <el-tag v-for="r in form.roleNames" :key="r" type="info" effect="plain" size="small">{{ r }}</el-tag>
                <span v-if="!form.roleNames || form.roleNames.length === 0">-</span>
              </el-space>
            </el-descriptions-item>
            <el-descriptions-item label="备注">{{ form.remark || '-' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(form.createTime) || '-' }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ formatDateTime(form.updateTime) || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <!-- 右侧：编辑表单 -->
      <el-col :span="16">
        <el-card class="edit-card" shadow="never">
          <template #header>
            <div class="card-header">
              <el-icon class="header-icon"><Edit /></el-icon>
              <span>编辑资料</span>
            </div>
          </template>

          <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名">
                  <el-input v-model="form.username" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="真实姓名" prop="realName">
                  <el-input v-model="form.realName" placeholder="请输入真实姓名" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入手机号" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="onSubmit" :loading="saving">保存</el-button>
              <el-button @click="onReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Edit } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { userApi } from '@/api/user'
import request from '@/api/request'

const auth = useAuthStore()
const formRef = ref()
const form = reactive({ ...auth.user })
const saving = ref(false)

// 获取用户角色信息
const fetchUserRoles = async () => {
  try {
    const response = await userApi.getUserRoleNames(form.id)
    if (response.data && response.data.code === 200) {
      form.roleNames = response.data.data || []
    } else {
      form.roleNames = []
    }
  } catch (error) {
    console.error('获取用户角色失败:', error)
    form.roleNames = []
  }
}

// 组件挂载时获取用户角色
onMounted(() => {
  fetchUserRoles()
})

const rules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度 2-20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 头像URL处理
const avatarUrl = computed(() => {
  const v = form.avatar || ''
  console.log('原始头像URL:', v) // 调试日志
  
  if (!v) {
    console.log('头像URL为空，返回空字符串')
    return ''
  }
  
  let finalUrl = v
  
  // 如果已经是完整的URL，直接返回
  if (v.startsWith('http://') || v.startsWith('https://')) {
    finalUrl = v
  }
  // 如果以/api开头，直接返回
  else if (v.startsWith('/api/')) {
    finalUrl = v
  }
  // 如果以/avatars开头，添加/api前缀
  else if (v.startsWith('/avatars/')) {
    finalUrl = '/api' + v
  }
  // 其他情况，直接返回
  else {
    finalUrl = v
  }
  
  console.log('处理后的头像URL:', finalUrl) // 调试日志
  return finalUrl
})

// 自定义上传：调用后端 /file/upload，返回URL；上传成功后自动保存资料
const handleAvatarUpload = async ({ file, onError, onSuccess }) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    const resp = await request({ url: '/file/upload', method: 'post', data: formData, headers: { 'Content-Type': 'multipart/form-data' } })
    if (resp.data && resp.data.code === 200) {
      form.avatar = resp.data.data // URL（可能带/api）
      // 自动保存，写入数据库
      const payload = { id: form.id, realName: form.realName, email: form.email, phone: form.phone, avatar: form.avatar, remark: form.remark }
      const saveResp = await userApi.updateUser(payload)
      if (saveResp.data.code === 200) {
        Object.assign(auth.user, payload)
        localStorage.setItem('user', JSON.stringify(auth.user))
        ElMessage.success('头像上传成功')
        onSuccess()
        return
      }
      ElMessage.error(saveResp.data.message || '保存失败')
      onError()
    } else {
      ElMessage.error(resp.data?.message || '上传失败')
      onError()
    }
  } catch (e) {
    ElMessage.error('上传失败')
    onError(e)
  }
}

const onSubmit = async () => {
  try {
    await formRef.value.validate()
    saving.value = true
    const payload = {
      id: form.id,
      realName: form.realName,
      email: form.email,
      phone: form.phone,
      avatar: form.avatar,
      remark: form.remark
    }
    const resp = await userApi.updateUser(payload)
    if (resp.data.code === 200) {
      Object.assign(auth.user, payload)
      localStorage.setItem('user', JSON.stringify(auth.user))
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(resp.data.message || '保存失败')
    }
  } finally {
    saving.value = false
  }
}

const onReset = () => { Object.assign(form, auth.user) }

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
}
</script>

<style scoped>
.profile-page { padding: 20px; }
.page-header { margin-bottom: 20px; padding: 20px; background: linear-gradient(135deg,#667eea 0%,#764ba2 100%); border-radius: 8px; color: #fff; }
.page-title { display: flex; align-items: center; font-size: 20px; font-weight: 600; }
.title-icon { margin-right: 8px; }

.profile-card { border-radius: 8px; }
.avatar-section { display: flex; flex-direction: column; align-items: center; padding: 10px 0 16px; }
.avatar-large { box-shadow: 0 4px 12px rgba(0,0,0,.12); }
.avatar-tip { margin-top: 8px; font-size: 12px; color: #909399; }
.profile-desc { margin-top: 10px; }

.edit-card { border-radius: 8px; }
.card-header { display: flex; align-items: center; gap: 6px; font-weight: 600; }
.header-icon { color: var(--el-color-primary); }
</style> 